package memberrewards.service;

import hackathon1212.ServletPojoAdapter;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
import memberrewards.delegate.RewardsDelegate;
import memberrewards.dtos.AccountDetailDTO;

public class RedeemPoints extends ServletPojoAdapter {
	private static final long serialVersionUID = 7479967700237495130L;
	protected Map<String,Object> getBusinessMethod(Map<String, String[]> params){
		//Query Params
		final String pan =params.get("pan")!=null? params.get("pan")[0]:null;
		final String pointsVal =params.get("pointsval")!=null? params.get("pointsval")[0]:null;
		
		//Default response
		final Map<String,Object> ret = new HashMap<String, Object>();
		ret.put("status", "Card Not Found");		
		ret.put("balance", "0");
		final AccountDetailDTO accountDetail = RewardsDelegate.getAccountDetail(pan);
		if (accountDetail!=null) {
			final BigInteger pointsBalance = new BigInteger(accountDetail.getPointBalance());
			try{
				final BigInteger pointsToRedeem = new BigInteger(pointsVal);
				if(pointsToRedeem.compareTo(pointsBalance) == -1 || pointsToRedeem.compareTo(pointsBalance) == 0){
					final BigInteger newPointsBalance=pointsBalance.subtract(pointsToRedeem);
					accountDetail.setPointBalance(newPointsBalance.toString());
					boolean status=RewardsDelegate.updateAccountDetail(accountDetail);
					System.out.println(getClass().getName()+" UpdateStatus ::"+status);
					ret.put("balance", newPointsBalance);
					ret.put("status", "Success");
				}
				else{
					ret.put("status", "Insufficient Points");
				}
			}
			catch(Exception ex){
				ret.put("status", "Invalid Points value");
			}
		}
		return ret;		
	}
	
//	protected Map<String,String> postBusinessMethod(Map<String, String[]> params){
//		final Map<String,String> ret = new HashMap<String, String>();
//		ret.put("status", "Success");	
//		ret.put("balance", "31768");
//		return ret;		
//	}

}
